package edu.mit.csail.relo.intro;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.progress.UIJob;

import edu.mit.csail.relo.intro.preferences.PreferenceConstants;

/**
 * @author vineet
 *
 */
public class ReloConnectionCheck implements IStartup {
	
	public final static String CONNECT_LABEL = "Connect";

	public void earlyStartup() {
		final IPreferenceStore prefStore = ReloIntroPlugin.getDefault().getPreferenceStore();

		if (!prefStore.getBoolean(PreferenceConstants.BuilderCheckConnectionAtStartupKey)) return;
		
		if (ReloJavaConnectionUtils.connectedToAllJavaProjects()) return;

		// ask the user and connect
		Job job = new UIJob("Connection Checker") {
			public IStatus runInUIThread(IProgressMonitor monitor) {
				MessageDialogWithToggle dialog = new MessageDialogWithToggle(
						null, // ignore shell
						"Relo Check", 
						null, // accept the default window icon
						"Relo is not connected to some of the Java Projects. Connect?", 
						MessageDialog.QUESTION, 
						new String[] { 
								CONNECT_LABEL,
		                        IDialogConstants.CANCEL_LABEL }, 0, // yes is the default button
                        PreferenceConstants.BuilderCheckConnectionAtStartupPrompt, 
                        prefStore.getBoolean(PreferenceConstants.BuilderCheckConnectionAtStartupKey)
		                ) {
					int connectId = -1;
				    protected Button createButton(Composite parent, int id, String label, boolean defaultButton) {
				    	if (label.equals(CONNECT_LABEL)) connectId = id;
				    	return super.createButton(parent, id, label, defaultButton);
				    }
					
					protected void buttonPressed(int buttonId) {
						super.buttonPressed(buttonId);
						prefStore.setValue(PreferenceConstants.BuilderCheckConnectionAtStartupKey, getToggleState());
				        if (buttonId == connectId ) {
				        	ReloJavaConnectionUtils.connectToAllJavaProjects();
				        }
					}
				};
				dialog.open();
				return Status.OK_STATUS;
			}
		};
		job.schedule();
	}

}
